package com.javaweb.servlet.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //对request和response进行强转
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;
        //获取请求路径
        String servletPath=request.getServletPath();
        HttpSession session=request.getSession(false);
        if ("/index.jsp".equals(servletPath) || "/register.jsp".equals(servletPath) ||"/user".equals(servletPath)
                || "/login".equals(servletPath)|| "/register".equals(servletPath)|| "/user/exit".equals(servletPath)
                || session!=null && session.getAttribute("user")!=null) {
            chain.doFilter(request,response);
        }else{
            //session中取不到相关的信息，跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
